package logic

import (
	"context"
	"encoding/json"
	"hema/cache"
	"hema/model/mysql"
	"time"

	"hema/hemarpc/hemarpc"
	"hema/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *hemarpc.ListRequest) (*hemarpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var products []mysql.Product
	result, _ := cache.Rdb.Get(l.ctx, "productList").Result()
	if result == "" {
		mysql.DB.Debug().Table("products").
			Select("products.*,classes.`name` as class_name").
			Joins("LEFT JOIN classes on products.class_id=classes.id").
			Find(&products)
		marshal, _ := json.Marshal(products)

		cache.Rdb.Set(l.ctx, "productList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &products)
	}
	var productList []*hemarpc.ProductList
	for _, product := range products {
		list := hemarpc.ProductList{
			Name:      product.Name,
			Price:     float32(product.Price),
			Stock:     product.Stock,
			Image:     product.Image,
			Info:      product.Info,
			ClassName: "",
			Product:   int64(product.ID),
		}
		productList = append(productList, &list)
	}
	return &hemarpc.ListResponse{
		List: productList,
	}, nil
}
